/*
 * @Author: 星孑
 * @Date: 2022-03-10 15:24:22
 * @LastEditors: 星孑
 * @LastEditTime: 2022-04-08 18:25:39
 * @FilePath: /admin/src/store/modules/user.js
 * @Description:
 */
import { login, getUserInfo } from '@/api/login'
import { setToken, removeToken } from '@/utils/auth'
import { cmdRSAEncrypt } from '@/utils/encrypt'

const user = {
  state: {
    userInfo: {}
  },

  mutations: {
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login({ username, password: cmdRSAEncrypt(userInfo.password) }).then(response => {
          const token = response
          setToken(token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(res => {
          const data = res
          commit('SET_USERINFO', data)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_USERINFO', {})
        removeToken()
        location.reload()
        resolve()
      })
    }
  }
}

export default user
